<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['routeprocess:routeprocess:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['routeprocess:routeprocess:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['routeprocess:routeprocess:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['routeprocess:routeprocess:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="routeprocessList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" />
      <el-table-column label="工序编码" align="center" prop="processCode" />
      <el-table-column label="工序名称" align="center" prop="processName" />
      <el-table-column label="序号" align="center" prop="orderNum" />
      <el-table-column label="与下一道工序关系" align="center" prop="linkType" />
      <el-table-column label="准备时间" align="center" prop="defaultPreTime" />
      <el-table-column label="等待时间" align="center" prop="defaultSufTime" />
      <el-table-column label="甘特图显示颜色" align="center" prop="colorCode">
        <template #default="scope">
          <div :style="{ backgroundColor: scope.row.colorCode, width: '20px', height: '20px', display: 'inline-block' }"></div>
          {{ scope.row.colorCode }}
        </template>
      </el-table-column>
      <el-table-column label="关键工序" align="center" prop="keyFlag" />
      <el-table-column label="是否检验" align="center" prop="isCheck" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['routeprocess:routeprocess:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['routeprocess:routeprocess:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
   <pagination
  v-show="total>0"
  :total="total"
  v-model:page="queryParams.pageNum"
  v-model:limit="queryParams.pageSize"
  @pagination="getList"
/>

    <!-- 添加或修改工艺组成对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="routeprocessRef" :model="form" :rules="rules" size="default" label-width="100px">
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label="序号" prop="orderNum">
              <el-input-number v-model="form.orderNum" placeholder="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序" prop="processName">
              <el-select v-model="form.processName" placeholder="请选择工序" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in processCodeOptions" :key="index" :label="item.processName"
                  :value="item.processCode" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label-width="140px" label="与下一道工序关系" prop="linkType">
              <el-select v-model="form.linkType" placeholder="请选择与下一道工序关系" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in linkTypeOptions" :key="index" :label="item.label"
                  :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label-width="120px" label="甘特图显示颜色" prop="colorCode">
              <el-color-picker
                v-model="form.colorCode"       
                show-alpha                     
                placeholder="请选择甘特图显示颜色"
                :predefine="predefineColors"   
              ></el-color-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="15">
          <el-col :span="11">
            <el-form-item label-width="110px" label="是否关键工序" prop="keyFlag">
              <el-select v-model="form.keyFlag" placeholder="请选择" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in keyFlagOptions" :key="index" :label="item.label"
                  :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label-width="140px" label="是否需要质检确认" prop="isCheck">
              <el-select v-model="form.isCheck" placeholder="请选择" clearable :style="{width: '100%'}">
                <el-option v-for="(item, index) in isCheckOptions" :key="index" :label="item.label"
                  :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="15">
          <el-col :span="10">
            <el-form-item label="准备时间" prop="defaultPreTime">
              <el-input-number v-model="form.defaultPreTime" placeholder="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="等待时间" prop="defaultSufTime">
              <el-input-number v-model="form.defaultSufTime" placeholder="0"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="15">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                placeholder="请输入内容"
                :autosize="{minRows: 4, maxRows: 4}" 
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Routeprocess">
import { listRouteprocess, getRouteprocess, delRouteprocess, addRouteprocess, updateRouteprocess } from "@/api/routeprocess/routeprocess";
import { listProcess } from "@/api/workstation/workstation";
import { getCurrentInstance, reactive, ref, toRefs } from "vue";
import Pagination from "@/components/Pagination";
import RightToolbar from "@/components/RightToolbar";

const { proxy } = getCurrentInstance();

// 预定义颜色（甘特图颜色选择器）
const predefineColors = ref([
  '#ff4500', '#ff8c00', '#ffd700', '#90ee90', 
  '#00ced1', '#1e90ff', '#c71585', '#808080'
]);

// 下拉选项数据（示例，需根据实际接口返回调整）
const processCodeOptions = ref([]); // 工序下拉
const linkTypeOptions = ref([
  { label: "连续", value: "CONTINUOUS" },
  { label: "并行", value: "PARALLEL" },
  { label: "等待", value: "WAIT" }
]); // 与下一道工序关系
const keyFlagOptions = ref([
  { label: "是", value: "Y" },
  { label: "否", value: "N" }
]); // 是否关键工序
const isCheckOptions = ref([
  { label: "是", value: "Y" },
  { label: "否", value: "N" }
]); // 是否需要质检确认

// 响应式数据
const routeprocessList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageDto: {
      current: 1,
      size: 10,
      routeId: null, // 关联工艺路线ID（关键！若无此条件可能查不到数据）
    },
  },
  rules: {
    // 工序（必填）
    processName: [
      { required: true, message: "工序不能为空", trigger: "blur" }
    ],
    // 是否关键工序（必填）
    keyFlag: [
      { required: true, message: "是否关键工序不能为空", trigger: "change" }
    ],
    // 是否需要质检确认（必填）
    isCheck: [
      { required: true, message: "是否需要质检确认不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询工艺组成列表 */
function getList() {
  loading.value = true;
  // 携带当前工艺路线 ID
  queryParams.value.pageDto.routeId = form.value.routeId;  
  listRouteprocess(queryParams.value)
    .then(response => {
      console.log("接口返回数据：", response);
      routeprocessList.value = response.data?.records || response.records || [];
      total.value = response.data?.pageDto?.total || response.total || 0;
    })
    .catch(error => {
      console.error("工艺组成查询失败：", error);
      routeprocessList.value = [];
      total.value = 0;
      proxy.$modal.msgError("查询数据失败，请重试");
    })
    .finally(() => {
      loading.value = false;
    });
}


// 查询工序下拉列表
function getProcessList() {
  loading.value = true;
  listProcess().then(response => {
    processCodeOptions.value = response.data;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    processName: null,
    orderNum: 1,
    linkType: null,
    defaultPreTime: 0,
    defaultSufTime: 0,
    colorCode: '#00AEF3',
    keyFlag: null,
    isCheck: null,
    remark: null,
    // 其他非必填字段可根据需求补充默认值
  };
  proxy.resetForm("routeprocessRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageDto.current = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getProcessList();
  form.value.routeId = /* 当前工艺路线ID，从父组件或路由获取 */
  open.value = true;
  title.value = "添加工艺组成";
  getList();
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _recordId = row.recordId || ids.value;
  getRouteprocess(_recordId).then(response => {
    form.value = response.data;
    // 确保拿到当前路线 ID
    form.value.routeId = row.routeId || response.data.routeId;  
    open.value = true;
    title.value = "修改工艺组成";
    // 修改弹窗打开时，也要刷新列表
    getList();
  });
}



/** 提交按钮 */
function submitForm() {
  proxy.$refs["routeprocessRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateRouteprocess(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRouteprocess(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value;
  proxy.$modal.confirm('是否确认删除工艺组成编号为"' + _recordIds + '"的数据项？').then(function() {
    return delRouteprocess(_recordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('routeprocess/routeprocess/export', {
    ...queryParams.value
  }, `routeprocess_${new Date().getTime()}.xlsx`);
}

// 初始化加载列表
getList();
</script>

<style scoped>
/* 可根据需要添加局部样式 */
.dialog-footer {
  text-align: right;
}
</style>